<template>
  <div class="vpt-base-tpl-1004">
    <div class="chart"
         ref="baseEchartRef"
         :style="{ ...echartStyle }"></div>
  </div>
</template>
<script setup>
import { fontSize } from "@/utils/rem/rem.js";
import * as echarts from "echarts/core";
import { computed, watch, ref, onMounted, nextTick } from "vue";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
} from "echarts/components";
import { LineChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { throttle } from "@/utils/throttle";

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer,
  LineChart,
  DataZoomComponent,
]);

// 设置图表宽高
const echartStyle = computed(() => {
  const { width, height } = props;
  // 判断是否已%结尾
  const reg = /%$/;
  return {
    width: reg.test(width) ? width : `${width}px`,
    height: reg.test(height) ? height : `${height}px`,
  };
});

const props = defineProps({

  // 图表宽度
  width: { type: String, default: "100%" },
  // 图表高度
  height: { type: String, default: "700" },
  // 图表配置项
  options: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

let baseChart = null;
const baseEchartRef = ref(null);
const chartOption = ref({});

const randerChart = () => {
  baseChart.setOption(chartOption.value, true);
};

const initChart = () => {
  if (!baseChart) {
    baseChart = echarts.init(baseEchartRef.value);
    randerChart();
    window.addEventListener("resize", () => {
      setTimeout(() => {
        baseChart.resize();
        throttle(getOption, 500)();
        randerChart();
      }, 100);
    });
  }
};
function getOption () {
  chartOption.value = {
    title: {
      text: props.options.title,
      left: '4%',
      textStyle: {
        color: "#fff",
        fontWeight: 400,
        height: fontSize(30),
        // fontFamily: "HarmonyOS_SansSC_Medium",
      },
    },
    xAxis: {
      type: "category",
      data: props.options.xAxisData ? props.options.xAxisData : [],
    },
    tooltip: {
      trigger: "axis",
    },
    yAxis: {
      name: '单位：' + props.options.unit,
      textStyle: {
        color: "#fff",
        fontWeight: 400,
        height: fontSize(30),
        // fontFamily: "HarmonyOS_SansSC_Medium",
      },
      type: "value",
    },
    series: [
      {
        data: props.options.seriesData ? props.options.seriesData : [],
        type: "line",
        showSymbol: false,
      },
    ],
  };
}

onMounted(() => {
  initChart();
});
</script>
<style lang="css" scoped>
@import url("./index.less");
</style>
